package cn.zn.framework.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.zn.framework.common.exception.RRException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;

@Slf4j
public class MysqlUtil {

    /**
     * 备份数据库
     *
     * @param dbName      数据库名称
     * @param dbHost      IP
     * @param dbPost      端口
     * @param dbUser      用户名
     * @param dbPwd       密码
     * @param binDirPath  mysql的bin目录地址
     * @param backDirPath 备份目录地址
     */
    public static void backDB(String dbName, String dbHost, String dbPost, String dbUser, String dbPwd, String binDirPath, String backDirPath) {
        String database = dbName;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        // 备份的路径地址
        String filepath = backDirPath.concat(File.separator).concat(database).concat("_").concat(sdf.format(Calendar.getInstance().getTime())).concat(".sql");
        //执行命令
        StringBuilder stmt = new StringBuilder(binDirPath.concat(File.separator).concat("mysqldump"));
        if (StrUtil.isNotBlank(dbHost)) {
            stmt.append(" -h").append(dbHost);
        }
        if (StrUtil.isNotBlank(dbPost)) {
            stmt.append(" -P").append(dbPost);
        }
        if (StrUtil.isNotBlank(dbUser)) {
            stmt.append(" --user=").append(dbUser);
        }
        if (StrUtil.isNotBlank(dbPwd)) {
            stmt.append(" --password=").append(dbPwd);
        }
        stmt.append(" ").append(database).append(" > ").append(filepath);
        log.info("运行命今：{}", stmt);
        try {
            String[] command = {"cmd", "/c", stmt.toString()};
            Process process = Runtime.getRuntime().exec(command);
            InputStream input = process.getInputStream();
            log.warn(IOUtils.toString(input, "UTF-8"));
            if (process.waitFor() == 0) {
                log.info("数据库备份成功");
            } else {
                //错误信息输出
                InputStream errorStream = process.getErrorStream();
                log.error(IOUtils.toString(errorStream, "gbk"));
            }
        } catch (IOException | InterruptedException e) {
            log.error("备份MYSQL数据库时出错", e);
            throw new RRException("备份MYSQL数据库时出错");
        }
    }
}
